import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/views/home/model/trial_drive_model.dart';
import 'package:yuan_hang_app/widget/sort_content.dart';
import 'package:yuan_hang_app/widget/status_btn.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_popup_window.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import '../../../../base/base_state.dart';
import '../../../../http/api.dart';
import '../../../../http/http_utils.dart';
import '../../../../res/w_constant.dart';
import '../../../../utils/router_helper.dart';
import '../../../../widget/custom_search.dart';
import '../../../../widget/tab_btn.dart';
import '../../../../widget/w_list_view.dart';
import '../../../../widget/w_toast.dart';
import 'book_cancel_page.dart';
import 'drive_registration_page.dart';
import 'drive_registration_detail_page.dart';

class TrialDrivePage extends StatefulWidget {
  const TrialDrivePage({super.key});

  @override
  BaseState<TrialDrivePage> createState() => _TrialDrivePageState();
}

class _TrialDrivePageState extends BaseState<TrialDrivePage> {
  int selectedIndex = 0; // 当前选中的标签索引，初始为全部
  List bookList = [];
  List<Map> tabList2 =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.driveStatus);
  List currentDriveList = [];
  List<Map> saleManList = WConstant().salesmanList;

  //已预约、签约中、待开始、试驾中、已结束、已取消

  Map sortParams = {};

  var mCurrentStatus;

  Map<String, dynamic> queryParams = {
    "pageNum": 1,
    "limit": 20,
  };

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "试驾列表",
        child: Column(
          children: <Widget>[
            // 文字标签按钮
            CustomSearch(
              hintText: "客户名称/手机号",
              onSortClick: () {
                // print("点击了排序")
                WPopupWindow.showSort(
                    context: context,
                    sortType: SortType.BOOK_DRIVE,
                    sortParams: sortParams,
                    isScrollControlled: false,
                    onSelected: (params) {
                      sortParams = params;
                      print("params$params");
                      params.forEach((key, value) {
                        queryParams[key] = value;
                        if (queryParams.containsKey(key) && value == null) {
                          queryParams.remove(key);
                        }
                      });
                      showLoading();
                      fetchDataList();
                    });
              },
              onTextChange: (text) {
                //   keyword = text;
                queryParams["queryParam"] = text;
                queryParams["pageNum"] = 1;
                showLoading();
                CommonUtils.antiShake(fetchDataList);
              },
            ),
            TabBtn(
              tabList: tabList2,
              paddingTop: 5.px,
              paddingBottom: 5.px,
              titleKey: "label",
              tabClick: (index) {
                queryParams["status"] =
                    index == 0 ? "" : tabList2[index]["value"];
                queryParams["pageNum"] = 1;
                showLoading();
                fetchDataList();
              },
            ),
            Expanded(
              child: WListView(
            //    padding: EdgeInsets.only(top: 10.px),
                itemBuilder: _noticeMsgItem,
                getDataList: (currentState, page) {
                  mCurrentStatus = currentState;
                  queryParams["pageNum"] = page;
                  fetchDataList();
                },
              ),
            ),
            GestureDetector(
              onTap: () {
                RouteHelper.pushWidget(context, const DriveRegistrationPage())
                    .then((isSave) {
                  if (isSave != null && isSave) {
                    fetchDataList();
                    setState(() {});
                  }
                });
              },
              child: Container(
                margin:
                    EdgeInsets.symmetric(vertical: 16.px, horizontal: 10.px),
                width: SizeUtils.screenW() - 48.px,
                alignment: Alignment.center,
                height: 48.px,
                decoration: BoxDecoration(
                  color: WColors.primaryColor,
                  borderRadius: BorderRadius.circular(24.px),
                ),
                child: WText(
                  "新增",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.px,
                  ),
                ),
              ),
            )
          ],
        ));
  }

  void fetchDataList() {
    print("当前选中的value是");
    print(tabList2[selectedIndex]["value"]);

    HttpUtils().post(Api.getTestDriveList, data: queryParams).then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        List list = value.data == null ? [] : value.data["records"];
        mCurrentStatus.onRefreshData(list, queryParams["pageNum"]);
        if (queryParams["pageNum"] == 1) {
          bookList.clear();
        }
        bookList.addAll(list);
      } else {
        mCurrentStatus?.onFail(value.errMsg);
      }
    }).catchError((e) {
      hideLoading();
    });
  }

  Widget _noticeMsgItem(context, index, currentDriveList) {
    Map item = currentDriveList[index];
    Map statusInfo = TrialDriveModel.exchangeStatus(
        CommonReqUtils.exchangeCodeToName(
            CommonReqUtils.driveStatus, item["status"]));
    return GestureDetector(
        onTap: () {
          RouteHelper.pushWidget(
              context, DriveRegistrationDetailPage(testDriveId: item["id"]));
        },
        child: Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(left: 10.px, right: 10.px, bottom: 8.px),
            padding: EdgeInsets.only(right: 10.px),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.px),
                color: Colors.white,
                boxShadow: const [
                  BoxShadow(
                      //线框阴影线条
                      color: WColors.border,
                      offset: Offset(0, 1),
                      blurRadius: 2)
                ]),
            child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  SizedBox(height: 5.px,),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Expanded(
                          child: Row(
                        children: [
                          WLine(
                            height: 16.px,
                            width: 4.px,
                            color: WColors.primaryColor,
                            marginRight: 10.px,
                          ),
                          Flexible(
                            flex: 1,
                            child: WText(
                              item["customerName"],
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                  fontSize: WDimens.tsLarge,
                                  color: WColors.mainTextColor,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                        ],
                      )),
                      StatusBtn(
                        width: 68.px,
                        height: 28.px,
                        color: statusInfo["color"],
                        text: CommonReqUtils.exchangeCodeToName(
                            CommonReqUtils.driveStatus, item["status"]),
                        isItemBtn: true,
                        isTag: true,
                      ),
                    ],
                  ),
                  WLine(
                    height: 1.px,
                    marginBottom: 5.px,
                    marginTop: 5.px,
                  ),
                  ItemSingleInfoRow(StringUtils.handleThePhoneStr(item["phone"])),
                  ItemInfoRow(
                      CommonReqUtils.exchangeCodeToName(
                          CommonReqUtils.driveType, item["driveType"]),
                      CommonReqUtils.exchangeCodeToName(
                          CommonReqUtils.driveMethod, item["driveMethod"])),
                  ItemInfoRow(
                      StringUtils.safeGetValue(CommonReqUtils.exchangeCodeToName(
                          CommonReqUtils.carType, item["modelId"]), placeHolder: "-"),
                      StringUtils.safeGetValue(item["saleMan"],
                          placeHolder: "未知")),
                  Padding(
                    padding: EdgeInsets.only(left: 10.px),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        WText(
                          "登记时间：${StringUtils.safeGetValue(item["registrationTime"])}",
                          style: TextStyle(
                              color: WColors.hintTextColor,
                              fontSize: WDimens.tsMedium),
                        ),
                        //只有试驾中或已结束才会有开始时间

                        Offstage(
                          offstage: (CommonReqUtils.exchangeCodeToName(
                                      CommonReqUtils.driveStatus,
                                      item["status"]) !=
                                  "试驾中" &&
                              CommonReqUtils.exchangeCodeToName(
                                      CommonReqUtils.driveStatus,
                                      item["status"]) !=
                                  "已结束"),
                          child: WText(
                            "开始时间：${StringUtils.safeGetValue(item["startDriveTime"])}",
                            style: TextStyle(
                                color: WColors.hintTextColor,
                                fontSize: WDimens.tsMedium),
                          ),
                        ),
                        Offstage(
                          offstage: (CommonReqUtils.exchangeCodeToName(
                                  CommonReqUtils.driveStatus, item["status"]) !=
                              "已结束"),
                          child: WText(
                            "结束时间：${StringUtils.safeGetValue(item["endDriveTime"])}",
                            style: TextStyle(
                                color: WColors.hintTextColor,
                                fontSize: WDimens.tsMedium),
                          ),
                        ),
                        Offstage(
                          offstage: (CommonReqUtils.exchangeCodeToName(
                                  CommonReqUtils.driveStatus, item["status"]) !=
                              "已取消"),
                          child: WText(
                            "取消时间：${StringUtils.safeGetValue(item["cancelTime"])}",
                            style: TextStyle(
                                color: WColors.hintTextColor,
                                fontSize: WDimens.tsMedium),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Offstage(
                    offstage: statusInfo["pressText"] == "" &&
                        statusInfo["openFlag"] == false,
                    child: WLine(
                      marginTop: 5.px,
                      height: 0.5.px,
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 5.px),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Offstage(
                          offstage: statusInfo["pressText"] == "",
                          child: StatusBtn(
                            height: 28.px,
                            width: 68.px,
                            color: WColors.primaryColor,
                            text: statusInfo["pressText"],
                            isItemBtn: true,
                            //  isTag: true,
                            onPressed: () {
                              switch (statusInfo["pressText"].toString()) {
                                case "登记":
                                  RouteHelper.pushWidget(
                                      context, const DriveRegistrationPage());
                                  break;
                                case "开始":
                                  //试驾开始
                                  String formattedDate = DateUtil.formatDate(
                                      DateTime.now(),
                                      format: DateFormats.full);
                                  Map<String, dynamic> dataMap = {
                                    "id": item["id"],
                                    "startDriveTime": formattedDate,
                                    "driveFrom":"24711001",
                                  };
                                  HttpUtils()
                                      .post(Api.saveTestDriveRegistrationInfo,
                                          data: dataMap)
                                      .then((data) {
                                    hideLoading();
                                    if (data.resultCode == 200) {
                                      Toast.toast("开始操作成功");
                                      bookList[index]["status"] = 10181002;
                                      bookList[index]["startDriveTime"] =
                                          formattedDate;
                                      setState(() {});
                                    } else{
                                      Toast.toast(data.errMsg ?? "");
                                    }
                                  });
                                  break;
                                case "结束":
                                  String formattedDate = DateUtil.formatDate(
                                      DateTime.now(),
                                      format: DateFormats.full);
                                  Map<String, dynamic> dataMap = {
                                    "id": item["id"],
                                    "endDriveTime": formattedDate,
                                    "driveFrom":"24711001",
                                  };
                                  showLoading();
                                  HttpUtils()
                                      .post(Api.saveTestDriveRegistrationInfo,
                                          data: dataMap)
                                      .then((data) {
                                    hideLoading();
                                    if (data.resultCode == 200) {
                                      Toast.toast("结束操作成功");
                                      bookList[index]["status"] = 10181003;
                                      bookList[index]["endDriveTime"] =
                                          formattedDate;
                                      setState(() {});
                                    } else {
                                      Toast.toast(data.errMsg ?? "");
                                    }
                                  });
                                  break;
                                case "取消":
                                  //更改状态为取消
                                  break;
                                default:
                                  // 可选：处理未知状态
                                  print("未知操作");
                              }
                            },
                          ),
                        ),
                        Offstage(
                            offstage: statusInfo["openFlag"] == false,
                            child: StatusBtn(
                              margin: EdgeInsets.only(left: 20.px),
                              height: 28.px,
                              width: 68.px,
                              color: WColors.border,
                              fontColor: WColors.mainTextColor,
                              text: "取消",
                              isItemBtn: true,
                              onPressed: () {
                                if (CommonReqUtils.exchangeCodeToName(
                                            CommonReqUtils.driveStatus,
                                            item["status"]) ==
                                        "试驾中" ||
                                    CommonReqUtils.exchangeCodeToName(
                                            CommonReqUtils.driveStatus,
                                            item["status"]) ==
                                        "待开始") {
                                  //只有已预约且已登记下才可以取消
                                  RouteHelper.pushWidget(
                                          context,
                                          DriveCancelPage(
                                              testDriveId: item["id"]))
                                      .then((isCancel) {
                                    if (isCancel) {
                                      String formattedDate =
                                          DateUtil.formatDate(DateTime.now(),
                                              format: DateFormats.full);
                                      item["status"] = 10181004;
                                      item["cancelTime"] = formattedDate;
                                      setState(() {});
                                    }
                                  });
                                }
                              },
                            ))
                      ],
                    ),
                  )
                ])));
  }


  Widget ItemSingleInfoRow(content) {
    //设置内容默认样式
    TextStyle textStyle = TextStyle(
      fontSize: WDimens.tsMedium,
      color: WColors.mainTextColor, // 默认文本颜色
    );
    return Container(
      margin: EdgeInsets.only(bottom: 5.px, left: 10.px),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          WText(
            content,
            style: textStyle,
          ),
        ],
      ),
    );
  }

  Widget ItemInfoRow(title, content) {
    //设置内容默认样式
    TextStyle textStyle = TextStyle(
      fontSize: WDimens.tsMedium,
      color: WColors.mainTextColor, // 默认文本颜色
    );

    if (content == "先生" || content == "女士") {
      textStyle = textStyle.copyWith(
          fontSize: WDimens.tsMedium, fontWeight: FontWeight.bold);
    }
    return Container(
      margin: EdgeInsets.only(bottom: 5.px, left: 10.px),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          WText(
            title,
            style: TextStyle(
                fontSize: WDimens.tsMedium, color: WColors.subTextColor),
          ),
          SizedBox(
            width: 10.px,
          ),
          WText(
            content ?? "",
            style: textStyle,
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    tabList2.insert(0, {"value": "0", "label": "全部"});
  }
}
